package com.dylan.datacollection;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dylan.datacollection.adapter.MsgListAdapter;
import com.dylan.datacollection.db.SharedPreferencesUtils;
import com.dylan.datacollection.entity.MsgEntity;
import com.dylan.datacollection.net.HttpConfig;
import com.dylan.datacollection.net.HttpHelper;
import com.dylan.datacollection.net.ResponseCallback;
import com.dylan.datacollection.utils.PermissionsChecker;
import com.dylan.datacollection.utils.ToastUtils;
import com.google.gson.Gson;
import com.obsessive.zbar.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Context context;
    TextView newMsgTitleText;
    TextView newMsgSummaryText;
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission_group.LOCATION
    };
    private final int ZBAR = 6813;
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    MsgEntity msgEntity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        mPermissionsChecker = new PermissionsChecker(this);
        findViewById(R.id.msg_button).setOnClickListener(this);
        findViewById(R.id.me_button).setOnClickListener(this);
        findViewById(R.id.rank_button).setOnClickListener(this);
        findViewById(R.id.scan_button).setOnClickListener(this);
        findViewById(R.id.map_button).setOnClickListener(this);
        newMsgTitleText = (TextView) findViewById(R.id.new_notice_title);
        newMsgSummaryText = (TextView) findViewById(R.id.new_notice_summary);
        findViewById(R.id.new_message).setOnClickListener(this);
        getMsgList();

    }

    public void getMsgList() {
        HttpHelper.getInstance().msgList(1,new ResponseCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(Object response, int id) {
                super.onResponse(response, id);
                try {
                    Log.i("msg", "response:" + response.toString());
                    JSONObject jsonObject = new JSONObject(response.toString());
                    if (jsonObject.optInt("code") == HttpConfig.SUCCESS) {
                        JSONArray jsonArr = jsonObject.optJSONArray("data");
                        List<MsgEntity> requestArrays = new ArrayList<MsgEntity>();
                        if (jsonArr.length() > 0) {
                            JSONObject jsonObj = jsonArr.getJSONObject(0);
                            Gson gson = new Gson();
                            msgEntity = gson.fromJson(new String(jsonObj.toString()), MsgEntity.class);
                            newMsgSummaryText.setText(msgEntity.getUpdated_date());
                            newMsgTitleText.setText(msgEntity.getTitle());
                        }


                    } else {
                        ToastUtils.showShortMsg(context, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.msg_button:
                intent.setClass(context, MsgListActivity.class);
                startActivity(intent);
                break;
            case R.id.map_button:
                intent.setClass(context, MapActivity.class);
                startActivity(intent);
                break;
            case R.id.me_button:
                if (!TextUtils.isEmpty(SharedPreferencesUtils.readToken(context))){
                    intent.setClass(context, MActivity.class);
                    startActivity(intent);
                }else{
                    intent.setClass(context, LoginActivity.class);
                    startActivityForResult(intent,6439);
                }

                break;
            case R.id.new_message:
                if (msgEntity!=null){
                    intent.setClass(context, MsgDetailActivity.class);
                    intent.putExtra("msg",msgEntity);
                    startActivity(intent);
                }
                break;
            case R.id.rank_button:
                intent.setClass(context, RankListActivity.class);
                startActivity(intent);
                break;
            case R.id.scan_button:
                if (!TextUtils.isEmpty(SharedPreferencesUtils.readToken(context))){
                    intent.setClass(context, CaptureActivity.class);
                    startActivityForResult(intent, ZBAR);
                }else{
                    intent.setClass(context, LoginActivity.class);
                    startActivityForResult(intent,6439);
                }

                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            startRequestPermission();
        }
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, PERMISSIONS, 321);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ZBAR) {
            if (data != null && !TextUtils.isEmpty(data.getStringExtra("result"))) {
                String result = data.getStringExtra("result");
                Intent intent = new Intent(context, ScoreActivity.class);
                intent.putExtra("id", result);
                startActivity(intent);
            }

        }else if(requestCode == 6439){
            ToastUtils.showLongMsg(context,"登录成功");
        }
    }
}
